﻿using Polenter.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Sharp.Interprocess
{
    internal static class SerializationUtil
    {
        private static SharpSerializer m_SharpSerializer;

        static SerializationUtil()
        {
            m_SharpSerializer = new SharpSerializer(new SharpSerializerBinarySettings()
            {
                Mode = BinarySerializationMode.Burst,
                IncludeAssemblyVersionInTypeName = true
            });
        }

        internal static byte[] Serialize<T>(T objectToSerialize)
        {            
            byte[] serializedObject;
            using (var memoryStream = new MemoryStream())
            {
                m_SharpSerializer.Serialize(objectToSerialize, memoryStream);
                serializedObject = memoryStream.ToArray();
            }
            return serializedObject;
        }

        internal static T Deserialize<T>(byte[] serializedObject)
        {
            T deserializedObject = default(T);
            using (var memoryStream = new MemoryStream(serializedObject))
            {
                try
                {
                    var retrievedObject = m_SharpSerializer.Deserialize(memoryStream);
                    deserializedObject = (T)retrievedObject;
                }
                catch (Exception e)
                {
                    Trace.WriteLine("Error fetching or casting serialized data. Generic parameter is incorrect or error in parameter byte array data");
                    Trace.WriteLine(e.ToString());
                }
            }

            return deserializedObject;
        }
    }
}
